package cn.com.generaldata.os.service.indicator_evaluation.incr_analysis;

 

 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Criteria;
import org.nutz.lang.random.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

 

import cn.com.generaldata.jsme_indicator_system.entity.IndicatorEvaluation;
import cn.com.generaldata.jsme_indicator_system.util.Constants;
import cn.com.generaldata.os.pojo.IndicatorEvaluationResult;
import cn.com.generaldata.os.service.indicator_evaluation.IndicatorEvaluationCalculateService;
import cn.com.generaldata.os.vo.IndicatorAccountVO;
 

/**
 * 海洋经济生产总值ARIMA评估指标计算类.
 */
public class GDOceanEconomyCalculateService_backup extends IndicatorEvaluationCalculateService {
	private static Logger log = LoggerFactory.getLogger(GDOceanEconomyCalculateService.class);

	/** 定期年份 */
	private int baseYear = 2001;
	 
	@Override
	protected Double calculate(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		Double result = null;
	//	String basePath = GDOceanEconomyCalculateService.class.getResource("").getPath().substring(1).replace("/", "\\\\");
		if (indicator.getSection() == Constants.INDICATOR_LEVEL_PROVINCE) {
			 //获取结果数据最大年
			 
			result = calculateProvinceResult(indicator, indicatorAccountVO);
			
		} else if (indicator.getSection() == Constants.INDICATOR_LEVEL_CITY) {
			// 市指标没确定先保留
		}
		return result;
	}
	
	/**
	 * 计算江苏省进出口总额增长率评估指标计算类.
	 * 
	 * @param indicator
	 * @param indicatorAccountVO
	 * @return
	 */
	private Double calculateProvinceResult(IndicatorEvaluation indicator, IndicatorAccountVO indicatorAccountVO) {
		
	 
		Double val = null;
		BufferedReader br=null ;
		try {
			
			Criteria cri = getIndicatorDataCri(indicatorAccountVO, indicatorAccountVO.getYear(), indicator.getId());
			Double indicatorVal_res = getEvaluationIndicatorValue(cri);
			//TBL_INDICATOR_EVALUATION_RES 当前年度无值,就取T_INDICATOR_INPUT表数据
			if (indicatorVal_res==null || indicatorVal_res.equals("")) {
				String paths = GDOceanEconomyCalculateService.class.getResource("").getPath().substring(1).replace("/", "\\\\");
				Double indicatorVal = getInputOrAccountingIndicatorValue(indicatorAccountVO,
						indicatorAccountVO.getYear(), indicator.getReference());
				//T_INDICATOR_INPUT表无值,就预测计算当前年的新值
				if ( indicatorVal==null || indicatorVal.equals("")) {
					//获取当前年的前一年和基准年之间的所有海洋生产总值数据
					String  res = getProsperityIndicatorData(indicatorAccountVO,indicator);
					//预测处理类
				//	cal =new PREDICTION_Gedpclass();
					/*MWArray[] MArr = new MWArray[res.length];
					for(int i=0;i<res.length;i++){
						MArr[i] = new MWNumericArray(res[i],MWClassID.DOUBLE);
					}*/
					//StringUtils.join(res, ",");
				
				//	MWNumericArray a= new MWNumericArray(res, MWClassID.DOUBLE);
				//	Object[] result = cal.PREDICTION_Gedp(1, res);
				//	MWNumericArray r = (MWNumericArray) result[0];
				//	int index = indicatorAccountVO.getYear() - baseYear;
				//	if (index < 0) {
				//		return null;
				//	}
					// matlab 数组从1开始,获取最后的一年度的预测值
				//	val = r.getDouble(index + 1);
					// -y 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 -gdp 587.50 672.86 792.19 928.42 1018.61 1287 1873.50 2114.50 2717.40 3550.90 4253.10 4723 5288.04 5849.36 6407.95
					String result="";
					Process proc = Runtime.getRuntime().exec("python  "+paths+"predict_test1.py"+res);
					//Process proc = Runtime.getRuntime().exec(args);
					proc.waitFor();
					br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
					
					String lineStr;
					while ((lineStr = br.readLine()) != null) {
						result += lineStr;
					}
			        System.out.println("-----"+result);
			        if(StringUtils.isNotBlank(result)){
			        	val =Double.parseDouble(result);
			        }
			        
				}else{
					
					val=indicatorVal;
				}
			}else{
				
				val=indicatorVal_res;
			}
			
			
		} catch (Exception e) {
			log.error("调用python计算海洋经济生产总值指标预测值错误", e);
			if (br !=null) {
				try {
					br.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			
		} finally {
			if (br !=null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return val;
	}

	/**
	 * 获取相关数据.
	 * 
	 * @param indicatorAccountVO
	 * @param indicatorNames
	 * @return
	 */
	private String getProsperityIndicatorData(IndicatorAccountVO indicatorAccountVO,IndicatorEvaluation indicator) {
		int yearLength = indicatorAccountVO.getYear() - baseYear;
		StringBuffer sBuffer = new StringBuffer(" -gdp");
		StringBuffer yBuffer = new StringBuffer(" -y");
		for (int i = 0; i < yearLength; i++) {
			int year = baseYear+i;
			Criteria cri = getIndicatorDataCri(indicatorAccountVO, year, indicator.getId());
			Double indicatorVal_res = getEvaluationIndicatorValue(cri);
			//TBL_INDICATOR_EVALUATION_RES 当前年度无值,就取T_INDICATOR_INPUT表数据
			if (indicatorVal_res==null || indicatorVal_res.equals("")) {
				Double indicatorVal = getInputOrAccountingIndicatorValue(indicatorAccountVO,
						year, indicator.getReference());
				//T_INDICATOR_INPUT表无值,就预测计算当前年的新值
				if ( indicatorVal==null || indicatorVal.equals("")) {
					BufferedReader br=null ;
					try {
						//如果此年度无值就进行预测，然后存入数据库，在返回值进行下一年度预测，最后一值到选择条件的前一年度。
						String paths = GDOceanEconomyCalculateService.class.getResource("").getPath().substring(1).replace("/", "\\\\");
						String result="";
						String res = yBuffer.toString()+sBuffer.toString();
						Process proc = Runtime.getRuntime().exec("python  "+paths+"predict_test1.py"+res);
						proc.waitFor();
						br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
						String lineStr;
						while ((lineStr = br.readLine()) != null) {
							result += lineStr;
						}
				        System.out.println("-----"+result);
				        if(StringUtils.isNotBlank(result)){
				        	//val =Double.parseDouble(result);
				        	sBuffer.append(" "+Double.parseDouble(result));//此年度无值
							yBuffer.append(" "+year);
							saveData(indicatorAccountVO,Double.parseDouble(result),indicator.getId(),year);
							//存储数据库
				        }
					}catch(Exception e){
						if (br !=null) {
							try {
								br.close();
							} catch (IOException e0) {
								log.error("调用python计算海洋经济生产总值指标预测值错误", e0);
							}
						}
					}finally {
						if (br !=null) {
							try {
								br.close();
							} catch (IOException e1) {
								log.error("调用python计算海洋经济生产总值指标预测值错误", e1);
							}
						}
					}
					
				}else{
					sBuffer.append(" "+indicatorVal);
					yBuffer.append(" "+year);
				}
			}else{
				sBuffer.append(" "+indicatorVal_res);
				yBuffer.append(" "+year);
			}	
		}
		return yBuffer.toString()+sBuffer.toString();
	}

	//保存中间空缺的预测值
	private void saveData(IndicatorAccountVO indicatorAccountVO,double result,Integer id,Integer year) {
		IndicatorEvaluationResult ier = new IndicatorEvaluationResult();
		ier.setIndicatorId(id);
		ier.setYearTime(indicatorAccountVO.getYearTime());
		ier.setIndicatorValue(result);
		ier.setTimeType(indicatorAccountVO.getTimeType());
		ier.setYear(year);
		ier.setAreaId(indicatorAccountVO.getAreaId());
		Criteria cri = getIndicatorEvaluationDataCri(ier);

		Record record = dao.fetch("tbl_indicator_evaluation_res", cri);
		if (record != null) {
			dao.clear("tbl_indicator_evaluation_res", cri);
		}
		saveEvaluationResult(ier);
	}
	
	private Criteria getIndicatorEvaluationDataCri(IndicatorEvaluationResult indicatorAccountVO) {
		Criteria cri = Cnd.cri();
		cri.where().and("indicator_id", "=", indicatorAccountVO.getIndicatorId());
		cri.where().and("time_type", "=", indicatorAccountVO.getTimeType());
		cri.where().and("year_time", "=", indicatorAccountVO.getYearTime());
		cri.where().and("area_id", "=", indicatorAccountVO.getAreaId());
		cri.where().and("year", "=", indicatorAccountVO.getYear());
		return cri;
	}
	
	
	private void saveEvaluationResult(IndicatorEvaluationResult ier) {
		// 保存新记录
		Chain chain = Chain.make("id", R.UU16());
		chain.add("indicator_id", ier.getIndicatorId());
		chain.add("area_id", ier.getAreaId());
		chain.add("time_type", ier.getTimeType());
		chain.add("year_time", ier.getYearTime());
		chain.add("year", ier.getYear());
		chain.add("indicator_value", ier.getIndicatorValue());
		dao.insert("tbl_indicator_evaluation_res", chain);
	}
	
}
